<template>
  <div class="components-layout-demo">
    <a-layout style="height:100%">
      <a-layout style="background: #fff;height:100%">
        <a-layout-sider class="layout-sider-left">
          <div style="height:100%;">
            <sidebar-role
              ref="roleMainTree"
              :checkable="false"
              @on-select="roleMainTreeSelect"
            ></sidebar-role>
          </div>
        </a-layout-sider>
        <a-layout-content class="layoutContent">
          <div class="components-table-demo-size" style="height:100%">
            <!-- tools盒子 每个页面必须存在的div盒子，除了表格以外的功能都放在这个里面 -->
            <div id="tools">
              <div class="height8"></div>
              <a-form layout="inline" style="text-align: left;padding: 0 10px;" :selfUpdate="true">
                <a-form-item label="关键字" class="marginBtm">
                  <a-input v-model="query.searchName"
                           allowClear placeholder="请输入用户名/姓名查询"
                           class="marginBtm"
                  />
                </a-form-item>


                <a-form-item class="marginBtm">
                  <a-button type="primary" @click="searching">
                    查询
                  </a-button>
                </a-form-item>

              </a-form>

              <a-divider style="margin: 5px 0"/>

              <!-- 功能按钮 -->
              <div class="divPadiAlign">
                <a-button v-if="isSuper == '是'" type="primary" class="button-marin" @click="openModal('新增账户')">
                  新增
                </a-button>
                <a-button v-if="isSuper == '是'" type="primary" class="button-marin" @click="openModal('编辑账户')">
                  修改
                </a-button>
                <a-button v-if="isSuper == '是'" type="primary" class="button-marin" @click="dateleUser">
                  删除
                </a-button>
              </div>

            </div>
            <!-- 右侧数据表格  :row-selection="rowSelection"-->
            <a-spin :spinning="spinning" tip="删除中...">
              <div id="tableBox" class="tableOthStyle">
                <a-table
                  ref="mainTable"
                  bordered
                  class="a-table"
                  size="small"
                  :columns="columns"
                  :dataSource="tableData"
                  :loading="loading"
                  :rowKey="(record) => record.id"
                  :pagination="pagination"
                  :scroll="{ y: yHeight,x:xWidth}"
                  :locale="localezh_CN"
                  :row-selection="rowSelection"
                  :customRow="selectRow"
                  :rowClassName="setRowClassName"
                >
                  <span slot="active" slot-scope="text,data">
                    <a @click="()=>confirmList(data)">设置区域</a>
                    <!--<a-divider type="vertical"/>-->
                    <!--<a @click="()=>seeDetails(data)">查看详情</a>-->
                  </span>

                </a-table>
              </div>
            </a-spin>
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>

    <!-- 模态框 -->
    <a-modal
      :destroyOnClose="true"
      :maskClosable="false"
      :keyboard="false"
      @ok="addAccountOk"
      @cancel="addAccountCancel"
      v-model="modalVisible"
      :dialog-style="{}"
      class="form"
      :title="modalTitle"
      width="680px"
      :bodyStyle="{padding: '20px'}"
      :okText="'保存'"
      :confirmLoading="confirmLoading"
    >
      <a-spin :spinning="modalLoading">
      <a-form :form="form">
        <a-row :gutter="20">
          <a-col :span="12">
            <a-form-item label="管理员账户" :colon="false" :label-col="{span: 7}" :wrapper-col="{span: 17}" required>
              <a-input
                :disabled="inputDisabled"
                @pressEnter="pressEnter"
                v-decorator="[
                  'userName',
                  {
                    rules: [
                      {type: 'string', required: true, message: '请输入工号，可回车查询填充' }
                      ]
                  },
                ]"
                placeholder="请输入管理员账户(工号)"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="真实姓名" :colon="false" :label-col="{span: 7}" :wrapper-col="{span: 17}" required>
              <a-input
                v-decorator="[
                  'realName',
                  {
                    rules: [
                      {type: 'string', required: true, message:'请输入真实姓名'}
                      ]
                  },
                ]"
                placeholder="请输入真实姓名"
              >
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <!--<a-row :gutter="20">-->
          <!--<a-col :span="12">-->
            <!--<a-form-item label="手机号" :colon="false" :label-col="{span: 7}" :wrapper-col="{span: 17}" :required="false">-->
              <!--<a-input-->
                <!--v-decorator="[-->
                  <!--'tel',-->
                  <!--{-->
                    <!--rules: [-->
                      <!--{type: 'string', required: false }-->
                      <!--]-->
                  <!--},-->
                <!--]"-->
                <!--placeholder="请输入手机号"-->
              <!--&gt;-->
              <!--</a-input>-->
            <!--</a-form-item>-->
          <!--</a-col>-->
          <!--<a-col :span="12">-->
            <!--<a-form-item label="电子信箱" :colon="false" :label-col="{span: 7}" :wrapper-col="{span: 17}" :required="false">-->
              <!--<a-input-->
                <!--v-decorator="[-->
                  <!--'email',-->
                  <!--{-->
                    <!--rules: [-->
                      <!--{ type: 'email' , message: '电子信箱格式有误!',},-->
                      <!--{required: false , message: '请输入电子信箱!',},-->
                      <!--]-->
                  <!--},-->
                <!--]"-->
                <!--placeholder="请输入电子信箱"-->
              <!--&gt;-->
              <!--</a-input>-->
            <!--</a-form-item>-->
          <!--</a-col>-->
        <!--</a-row>-->
        <a-row :gutter="20">
          <a-col :span="12">
            <a-form-item label="密码" :colon="false" :label-col="{span: 7}" :wrapper-col="{span: 17}" required>
              <a-input-password
                v-decorator="[
                  'password',
                  {
                    rules: [
                      {type: 'string',  required: true, message: '请输入密码' },
                      { validator: validateToNextPassword,}
                      ]
                  }
                ]"
                placeholder="请输入密码"
              >
              </a-input-password>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="确认密码" :colon="false" :label-col="{span: 7}" :wrapper-col="{span: 17}" required>
              <a-input-password
                v-decorator="[
                  'qrPassword',
                  {
                    rules: [
                      {type: 'string',  required: true, message: '请输入确认密码' },
                      { validator: compareToFirstPassword,}
                      ]
                  }
                ]"
                placeholder="请输入确认密码"
              >
              </a-input-password>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col style="padding-left: 14px">
            <a-form-item label="权限组" :colon="false" :label-col="{span: 3}" :wrapper-col="{span: 18}"  required>
              <a-tree-select
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择权限组"
                tree-default-expand-all
                allow-clear
                multiple
                @change="changeRole"
                v-decorator="[
                  'roleIds',
                  {
                    rules: [
                      {type: 'array',  required: true, message: '请选择权限组' },
                      ]
                  }
                ]"

              >
              </a-tree-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
        <div class="flex" style="min-height: 100px;" v-if="noarea">
          暂无可设置的区域，请选择权限组
        </div>
        <div style="min-height: 200px;" v-else>
          <sidebar-menu
            ref="menuTree"
            :checkable="true"
            @on-check="menuMainTreeCheck"
            @on-select="menuMainTreeSelect"
            :heightTree="{ height: '180px' }"
            :checkedKeys.sync="areaId"
            :checkedKey="areaId"
            :type="2"
          />
        </div>
      </a-spin>
    </a-modal>

    <set-area-tree
      ref="menuMainTree"
      :checkable="true"
      @on-check="areaMainTreeCheck"
      @okSave="okSave"
      :checked-keys.sync="menuCheckedKeys"
      :checkedKey="menuCheckedKeys"
    ></set-area-tree>
  </div>
</template>

<script>
import localezh_CN from 'antd/lib/locale-provider/zh_CN'
import {tableBoxHeight} from "@/api/communal";
import sidebarRole from "@/components/sidebarRole.vue";
import setAreaTree from "@/components/setAreaTree.vue";
import adminsDefinitionApi from "@/api/visitorSystem/adminsDefinition";
import sidebarMenu from "@/components/accessControlSystem/sidebarMenu.vue";
import role from "@/api/accessControlSystem/role";

export default {
  components: {
    sidebarRole,setAreaTree,sidebarMenu
  },
  name: 'adminsDefintion',
  data() {
    return {
      localezh_CN,
      xWidth: '',
      yHeight: '',
      tableData: [],
      pagination: false,
      selectedRowKeys: [],
      selectedRows: [],
      loading: false,
      queryValue: '', // 查询值,访客名称，访客手机号
      columns: [], // 表格表头,
      state:{
        rowId:null
      },
      //查询参数
      query: {
        searchName: null,
        checkIds: [],
        selectId:[],
      },
      menuCheckedKeys:[],
      menuTrees:[],
      nowRow:{},
      //新增账户参数
      addparam: {
        id: "",
        account: "",
        userName:"",
        phoneNumber:"",
        email:"",
        password:"",
        qrPassword:"",
        roleId:""
      },
      roleList:[],
      modalVisible: false,
      modalTitle: "",
      inputDisabled: false,
      form: this.$form.createForm(this, {name: 'accountFrom'}),
      treeData:[],
      //新增/修改保存按钮loading
      confirmLoading:false,
      modalLoading:false,
      spinning:false,
      areaId:[],
      isSuper:"",
      noarea: true
    }
  },
  beforeMount() {
    this.columns = [
      {
        title: '序号', // 表头
        dataIndex: 'serialNumber', // 字段名称
        width: '50px', // 设列宽度
        align: 'center', // 居中显示
        fixed: "left",
        className: 'changeBack', // 重置覆盖背景色为浅灰色，否则是白色的
        customRender: (value, row, index) => `${index + 1}` // 设置动态序号
      },
      {
        title: '用户名',
        dataIndex: 'userName',
        width: '100px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '真实姓名',
        dataIndex: 'realName',
        width: '100px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '创建人',
        dataIndex: 'creationUser',
        width: '100px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: '150px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      // {
      //   title: '操作',
      //   dataIndex: 'active',
      //   width: '150px',
      //   align: 'center',
      //   className: 'changeBack',
      //   scopedSlots: { customRender: "active" }
      // },
      {
        title: '最后操作人',
        dataIndex: 'updateUser',
        width: '100px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '操作时间',
        dataIndex: 'updateTime',
        width: '150px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '',
        dataIndex: '',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
  ]

  },
  created() {

  },
  destroyed() {

  },
  mounted() {
    //多加上没有分页条的高度
    this.yHeight = tableBoxHeight() + 53 + 'px';
    this.xWidth = this.getTableWidth();
    this.getRuleMaintwo();
    this.checkIsSuper();

  },
  computed:{
    //展示页面复选框
    rowSelection() {
      let _this = this;
      return {
        fixed: true,
        selectedRowKeys:_this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          _this.selectedRowKeys = selectedRowKeys;
          _this.selectedRows = selectedRows;
          // console.log(_this.selectedRows)
        },
        onSelect: (record, selected, selectedRows) => {
          //console.log(record, selected, selectedRows);
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
          //console.log(selected, selectedRows, changeRows);
        }
      };
    },
  },
  methods: {
    openModalss(){
      this.$refs.menuMainTree.open()
    },
    //查询按钮
    searching() {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      let param={
        roleIds:this.query.selectId.join(","),
        searchText:this.query.searchName
      }
      //查询
      this.loading = true;
      adminsDefinitionApi.getAccountList(param).then(res=>{
        this.loading = false;
        if (res.data.success) {
          this.tableData = res.data.result;
        } else {
          this.$message.error(res.data.message);
        }
      })
    },
    //查询登陆人是否是超级管理员
    checkIsSuper() {
      adminsDefinitionApi.checkIsSuper().then(res=>{
        // console.log(res);
        if (res.data.success) {
          this.isSuper = res.data.result.isSuper;
          this.$nextTick(()=>{
            this.yHeight = tableBoxHeight() + 53 + 'px';
            let minHeight = document.getElementsByClassName("ant-table");
            minHeight[0].style.minHeight = tableBoxHeight() + 93 + "px";
          })
        } else {
          this.$message.error(res.data.message);
        }
      })
    },
    // 计算表格宽度
    getTableWidth() {
      let totals = null
      var el
      for (el of this.columns) {
        totals += parseInt(el.width)
      }
      return totals + 100 + 'px'
    },
    //添加/修改账户
    addAccountOk(e) {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        let param = this.form.getFieldsValue();
        // console.log(param);
        //编辑账户时，取修改的人员ID
        if(this.modalTitle=="编辑账户"){
          //添加ID参数
          let row = this.selectedRows[0];
          param.id = row.id;
          param.employeeId = row.employeeId;
          param.createId = row.createId;
          param.createTime = row.createTime;
          param.tel = "";
          param.email = "";
        }
        param.areaIds = this.areaId.join(",");
        this.confirmLoading = true;
        this.modalLoading = true;
        adminsDefinitionApi.addOrUpdateUser(param).then(res=>{
          if (res.data.success) {
            this.confirmLoading = false;
            this.modalLoading = false;
            this.$message.success(res.data.message);
            this.addAccountCancel();
            this.searching();
          } else {
            this.confirmLoading = false;
            this.modalLoading = false;
            this.$message.error(res.data.message);
          }
        })
      })
    },
    //打开新增/修改弹窗
    openModal(title) {
      this.modalTitle = title;

      if(title=="新增账户"){
        this.inputDisabled = false;
        this.noarea = true;
        this.modalVisible = true;
      }else {
        if(this.selectedRows.length == 1){
          this.modalVisible = true;
          this.inputDisabled = true;
          let row = this.selectedRows[0];
          this.$nextTick(()=>{
            // 区域根据权限组id获取，区域配置树放在弹窗里
            this.changeRole(row.roleIdStr.split(","));
          })
          //初始化赋值
          this.form.getFieldDecorator("userName", {"initialValue":row.userName});
          this.form.getFieldDecorator("realName", {"initialValue":row.realName});
          // this.form.getFieldDecorator("tel", {"initialValue":row.tel});
          // this.form.getFieldDecorator("email", {"initialValue":row.email});
          this.form.getFieldDecorator("password", {"initialValue":row.password});
          this.form.getFieldDecorator("qrPassword", {"initialValue":row.password});
          this.form.getFieldDecorator("roleIds", {"initialValue":row.roleIdStr.split(",")});
        }else {
          this.$message.warning("请需要一个要修改的账户");
          return false;
        }
      }
    },
    //取消、关闭弹窗
    addAccountCancel() {
      this.modalLoading = false;
      this.confirmLoading = false;
      this.modalVisible = false;
    },
    //删除管理员
    dateleUser() {
      let _this = this;
        if(null!=this.selectedRowKeys && this.selectedRowKeys.length>0){
          //删除确认
          this.$confirm({
            title: '删除确认',
            content: '确定要删除已勾选的管理员账户吗？',
            okText: '确认',
            cancelText: '取消',
            onOk() {
              //删除
              let param = {
                userIds:_this.selectedRowKeys
              }
              _this.spinning = true
              adminsDefinitionApi.deleteAccount(param).then(res=>{
                _this.spinning = false
                if (res.data.success) {
                  _this.$message.success(res.data.message);
                  _this.searching();
                } else {
                  _this.$message.error(res.data.message);
                }
              })
            },
          });
        }else{
          this.$message.warning("请勾选需要删除的账户");
        }
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form;
      if (value && value !== form.getFieldValue('password')) {
        callback('两次密码不一致!');
      } else {
        callback();
      }
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form;
      if (value && this.confirmDirty) {
        form.validateFields(['qrPassword'], {force: true});
      }
      callback();
    },
    roleMainTreeSelect(v){
      // console.log(v);
      this.query.selectId = v;
      this.searching();
    },
    selectRow(record){
        return {
          props: {

          },
          on: { // 事件
            click: (event) => {
              if(this.selectedRowKeys.indexOf(record.id) > -1){
                this.selectedRows = this.selectedRows.filter(v=>{
                  return v.id!=record.id
                })
                this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record.id),1)
              }else{
                this.selectedRows.push(record)
                this.selectedRowKeys.push(record.id)
              }
            },       // 点击行
            dblclick: (event) => {
            },
            contextmenu: (event) => {
            },
            mouseenter: (event) => {
            },  // 鼠标移入行
            mouseleave: (event) => {
            }
          },
        }
    },
    setRowClassName(record){
      return this.selectedRowKeys.indexOf(record.id) > -1 ? 'clickRowStyl' : '';
    },
    pressEnter(e){
        let param = this.form.getFieldsValue(['userName']);
        // console.log(param);
        this.modalLoading = true;
        adminsDefinitionApi.getUserListByUserNo({userNo: param.userName.trim()}).then(res=>{
          // console.log(res)
          if (res.data.success) {
            this.modalLoading = false;
            let userinfo = res.data.result[0];
            this.form.getFieldDecorator("realName", {"initialValue":userinfo.userLname});
            // userLname: "田锐东"
            // userNo: "28018212"
            // userSerial: 20011248
          } else {
            this.modalLoading = false;
            this.$message.error(res.data.message);
          }
        })
    },

    areaMainTreeCheck(v){
      // console.log(v);
      this.menuCheckedKeys = v;
    },
    // 保存区域配置
    okSave(){
      // console.log(this.menuCheckedKeys);
      // console.log(this.nowRow);
      adminsDefinitionApi.addRoleUserArea({
        userId: this.nowRow.id,
        areaIds: this.menuCheckedKeys.join(",")
    }).then(res=>{
        if (res.data.success) {
          this.$message.success(res.data.message);
          this.$refs.menuMainTree.close();
        } else {
          this.$refs.menuMainTree.confirmLoading = false;
          this.$message.error(res.data.message);
        }
      })
    },
    // 获取区域配置并回显，根据人员id获取——修改时（弃用）
    confirmList(row){
      // console.log(row);
      this.nowRow = row;
      adminsDefinitionApi.getAreaAndBaseByRole({
        userId: this.nowRow.id
      }).then(res=>{
        if (res.data.success) {
          // 原来的表格行中的设置区域弹窗
          // this.menuCheckedKeys = res.data.result.areaIds.split(",");
          // console.log(this.menuCheckedKeys);

          this.areaId = res.data.result.areaIds.split(",");
          // console.log(this.areaId);
          if (res.data.result.tree.length == 0) {
            this.$message.warning("你的权限没有可以设置的区域节点");
          } else {
            // 原来的表格行中的设置区域弹窗
            // this.$refs.menuMainTree.open();
            // this.$nextTick(()=>{
            //   this.$refs.menuMainTree.setMenuTree(res.data.result.tree,this.menuCheckedKeys);
            // })

            this.$refs.menuTree.setMenuTree(res.data.result.tree, this.areaId );
          }

        } else {
          this.$message.error(res.data.message);
        }
      })
    },
    changeRole(value){
      // console.log(value);
      if (value.length == 0){
        this.noarea = true;
      } else {
        this.noarea = false;
        this.getAreaAndBased(value);
      }

    },
    // 获取权限区域，根据权限组获取——新增修改时（20211012变更）
    getAreaAndBased(value){
      let _this = this;
      adminsDefinitionApi.getAreaAndBaseByRoletwo({
        groupIds: value.join(","),
        userId: this.modalTitle=="新增账户"?"":this.selectedRows[0].id
      }).then(res=>{
        if (res.data.success) {
          // console.log(res.data.result);
          this.areaId = res.data.result.areaIds.split(",");
          if (res.data.result.tree.length == 0) {
            this.$message.warning("没有可以设置的区域");
          } else {
            this.$nextTick(()=>{
              _this.$refs.menuTree.setMenuTree(res.data.result.tree,_this.areaId);
            })
          }

        } else {
          this.$message.error(res.data.message);
        }
      })
    },

    menuMainTreeSelect(v) {
      this.areaId = v;
    },
    menuMainTreeCheck(v) {
      this.areaId = v;
    },
    // 根据权限获取权限组
    getRuleMaintwo(){
      role.getRuleMaintwo().then(res => {
        // console.log(res);
        if (res.data.success){
          this.treeData = res.data.result;
        } else {
          this.$message.warning(res.data.message);
        }
      });
    },



  },
}
</script>
<style>
.clickRowStyl{
  background-color:#D8E6DF !important
}
.ant-table-tbody>.clickRowStyl>td{
  background-color:#D8E6DF !important
}
</style>
